<template>
    <el-dialog :model-value="showAddVideoVisible" :title="props.editInfo.id ? '编辑图标' : '新增图标'" width="700"
        :close-on-click-modal="false" @close="resetForm">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="排序" prop="sort">
                <el-input v-model="ruleForm.sort" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="图标标题" prop="questionName">
                <el-input v-model="ruleForm.questionName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="图标描述" prop="answer">
                <el-input v-model="ruleForm.answer" type="textarea" :rows="5" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="图标封面" prop="questionImg">
                <el-input v-model="ruleForm.questionImg" style="display: none"></el-input>
                <div class="avatar-uploader" @click="showImageChooseDialog = true">
                    <el-image v-if="ruleForm.questionImg" :src="ruleForm.questionImg" class="avatar"
                        fit="contain"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                            <Plus />
                        </el-icon></i>
                    <div v-if="ruleForm.questionImg" class="mask">替换</div>
                    <el-icon v-if="ruleForm.questionImg" class="del-image" :size="20" @click.stop="handleDelImg">
                        <CircleCloseFilled />
                    </el-icon>
                </div>
            </el-form-item>
            <!-- <el-form-item label="状态" prop="isDisplay">
                <el-switch v-model="ruleForm.isPay" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)">确认</el-button>
                <el-button @click="resetForm">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
        :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
        :operationType="false"></image-selected-dialog>
    <video-group-dialog v-if="showVideoChooseDialog" :show-video-choose-dialog="showVideoChooseDialog"
        :single-type="singleType" :operation-type="false" @close-dialog="handleCloseVideoDialog" />
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { getcarmodellist, addVideoData, putquestioncategory } from '@/api/questionbank'
import { Plus } from '@element-plus/icons-vue'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import VideoGroupDialog from '@/views/decoration/diyComponents/VideoGroupDialog.vue'

const userStore = useUserStore()

const props = defineProps({
    showAddVideoVisible: {
        type: Boolean
    },
    editInfo: {
        type: Object,
        default: () => {
            return {
                id: ''
            }
        }
    },
    groupInfo: {
        type: Object,
        default: () => {
            return {
                id: ''
            }
        }
    },
    groupId: {
        type: [String, Number],
        default: ''
    }
})

const emit = defineEmits(['closeDialog'])

let server = `${import.meta.env.VITE_API_URL}files`
let { accessToken } = userStore
const imgheaders = { Authorization: 'Bearer ' + accessToken }
const editLoading = ref(false)
const carList = ref<Array<carLists>>([])
interface carLists {
    label: string
    value: string
    tag: string
}
interface RuleForm {
    sort: string
    questionName: string
    videoUrl: string
    answer: string
    isPay: number
    questionImg?: string
    carIds: string
}

const ruleFormRef = ref<FormInstance>()
let loadingMessage: ReturnType<typeof ElMessage> | null = null

const ruleForm = reactive<RuleForm>({
    sort: '1',
    questionName: '',
    answer: '',
    videoUrl: '',
    isPay: 1,
    questionImg: '',
    carIds: ''
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const singleType = ref(true)
const showVideoChooseDialog = ref(false)
const handleCloseImageDialog = (value: any) => {
    if (value && value.fileUrl) { ruleForm.questionImg = value.fileUrl }
    showImageChooseDialog.value = false
}
const handleCloseVideoDialog = (value: any) => {
    if (value && value.fileUrl) { ruleForm.videoUrl = value.fileUrl }
    showVideoChooseDialog.value = false
}

const handleDelImg = () => {
    ruleForm.questionImg = ''
}

const rules = reactive<FormRules<RuleForm>>({
    sort: [{ required: true, message: '不能为空', trigger: 'blur' }],
    questionName: [{ required: true, message: '不能为空', trigger: 'blur' }],
    answer: [{ required: true, message: '不能为空', trigger: 'blur' }],
    videoUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
    isPay: [{ required: true, message: '不能为空', trigger: 'change' }],
    questionImg: [{ required: true, message: '不能为空', trigger: 'change' }]
})


const handleAvatarSuccess = (file: any) => {
    ruleForm.videoUrl = file.data.url

    loadingMessage?.close()
    ElMessage({
        showClose: true,
        message: '图标上传成功！',
        type: 'success'
    })
}
//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
    loadingMessage = ElMessage({
        message: '图标上传中，请稍后...',
        type: 'info',
        duration: 0,
        showClose: false
    })

    const isVideo = file.type.startsWith('video/')
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isVideo) {
        ElMessage.error('只能上传图标文件')
        loadingMessage?.close()
        return false
    }
    if (!isLt100M) {
        ElMessage.error('图标大小不能超过 100MB')
        loadingMessage?.close()
        return false
    }

    return true
}

const handleError = () => {
    loadingMessage?.close()
    ElMessage({
        showClose: true,
        message: '上传失败，请稍后重试',
        type: 'error'
    })
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if (props.editInfo.id) {
                handleEdit()
            } else {
                handleAdd()
            }
        } else {
        }
    })
}

async function handleAdd() {
    try {
        editLoading.value = true
        const res = await addVideoData({
            ...ruleForm,
            groupIds: props.groupInfo.id
        })
        if (res.code === '00000') {
            emit('closeDialog', true)
            ElMessage.success('新增成功')
        }
    } catch (e) {
    } finally {
        editLoading.value = false
    }
}

async function handleEdit() {
    try {
        editLoading.value = true
        const res = await putquestioncategory.putquestioncategoryId(props.editInfo.id, {
            ...ruleForm,
            groupId: props.groupId
        })
        if (res.code === '00000') {
            emit('closeDialog', true)
            ElMessage.success('编辑成功')
        }
    } catch (e) {
    } finally {
        editLoading.value = false
    }
}

//车型下拉接口
const getcarmodellistinfo = async () => {
    let obj = {}
    const res = await getcarmodellist.getcarmodelId(obj)
    if (res.code == 0) {
        carList.value = res.data
    }
}

const resetForm = () => {
    emit('closeDialog')
}
onMounted(() => {
    if (props.editInfo.id) {
        ruleForm.sort = props.editInfo.sort
        ruleForm.isPay = props.editInfo.isPay
        ruleForm.questionName = props.editInfo.questionName
        ruleForm.videoUrl = props.editInfo.videoUrl
        ruleForm.answer = props.editInfo.answer
        ruleForm.videoUrl = props.editInfo.videoUrl
        ruleForm.questionImg = props.editInfo.questionImg
    }
    ruleForm.carIds = props.groupInfo.carIds
    getcarmodellistinfo()
})
</script>

<style scoped lang="scss">
.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;

    .mask {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 24px;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s ease;
        color: #fff;
        font-size: 12px;
    }

    .del-image {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        color: #8c939d;
    }

    &:hover .mask {
        opacity: 1;
    }

    &:hover .del-image {
        display: block;
    }
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>